package com.wh.wisdomsite.xbox.common.util;

import com.wh.wisdomsite.xbox.common.Constants;
import com.wh.wisdomsite.xbox.common.reponse.CommonResult;
import com.wh.wisdomsite.xbox.utils.Const;
import com.wh.wisdomsite.xbox.utils.StringUtils;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil_Google;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil_Org;
import org.json.JSONException;
import org.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.*;

/**
 * <pre>
 * 功能说明：
 * </pre>
 *
 * @author launchso
 * @version 1.0
 */
public class XboxUtils {

    private static final Log logger = LogFactory.getLog(XboxUtils.class);

    /**
     * 使用<code>secret</code>对paramValues按以下算法进行签名： <br/>
     * uppercase(hex(sha1(secretkey1value1key2value2...secret))
     *
     * @param paramValues 参数列表
     * @param secret
     * @return
     */
    public static String sign(Map<String, String> paramValues, String secret) {
        return sign(paramValues, null, secret);
    }

    /**
     * 对paramValues进行签名，其中ignoreParamNames这些参数不参与签名
     *
     * @param paramValues
     * @param ignoreParamNames
     * @param secret
     * @return
     */
    public static String sign(Map<String, String> paramValues, List<String> ignoreParamNames, String secret) {
        try {
            StringBuilder sb = new StringBuilder();
            List<String> paramNames = new ArrayList<String>(paramValues.size());
            paramNames.addAll(paramValues.keySet());
            if (ignoreParamNames != null && ignoreParamNames.size() > 0) {
                for (String ignoreParamName : ignoreParamNames) {
                    paramNames.remove(ignoreParamName);
                }
            }
            Collections.sort(paramNames);

            sb.append(secret);
            for (String paramName : paramNames) {
                sb.append(paramName).append(paramValues.get(paramName));
            }
            sb.append(secret);
//            System.out.println(sb.toString());
            byte[] sha1Digest = getSHA1Digest(sb.toString());
            return byte2hex(sha1Digest);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String utf8Encoding(String value, String sourceCharsetName) {
        try {
            return new String(value.getBytes(sourceCharsetName), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new IllegalArgumentException(e);
        }
    }

    private static byte[] getSHA1Digest(String data) throws IOException {
        byte[] bytes = null;
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            bytes = md.digest(data.getBytes("UTF-8"));
        } catch (GeneralSecurityException gse) {
            throw new IOException(gse);
        }
        return bytes;
    }

    private static byte[] getMD5Digest(String data) throws IOException {
        byte[] bytes = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            bytes = md.digest(data.getBytes("UTF-8"));
        } catch (GeneralSecurityException gse) {
            throw new IOException(gse);
        }
        return bytes;
    }

    /**
     * 二进制转十六进制字符串
     *
     * @param bytes
     * @return
     */
    private static String byte2hex(byte[] bytes) {
        StringBuilder sign = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() == 1) {
                sign.append("0");
            }
            sign.append(hex.toUpperCase());
        }
        return sign.toString();
    }


    /***
     * 获取响应数据
     * @param commonResult 返回结果
     * @param json 服务器数据
     * @param cls 映射对象
     * @param listKey  集合名称
     * @return
     */
    public static CommonResult getCommonResult(CommonResult commonResult, String json, Class cls, String listKey[]){
        //创建jsonObject对象
        org.json.JSONObject jsonObject;
        try {
            if(StringUtils.isEmpty(json)){
                commonResult.setMessage(Constants.RETURN_NETWORK_EXCEIPTION);
                commonResult.setCode(Constants.CODE_FAIL);
                commonResult.setResult(new JSONObject());
                return commonResult;
            }
            jsonObject = new JSONObject(json);
            //获取返回编码
            String resCode = JsonUtil_Org.getValueByKey(jsonObject, Constants.RESCODE);
            //获取返回消息
            String resMsg = JsonUtil_Org.getValueByKey(jsonObject, Constants.RESMSG);
            //获取返回结果
            String result = JsonUtil_Org.getValueByKey(jsonObject, Constants.RESULT);
            //响应成功
            if(Constants.CODE_SUCCESS.equalsIgnoreCase(resCode)) {
                //设置相应消息
                commonResult.setMessage(resMsg);
                //设置相应编码
                commonResult.setCode(resCode);
                if(cls != null){
                    //创建一个Map对象
                    Map<String, Object> hashMap = null;
                    //返回结果
                    String resultObject = "";
                    //判断取值Key
                    if(null != listKey){
                        //hashMap初始化
                        hashMap  = new HashMap<String, Object>();
                        //单个集合输出(无key)
                        if(0 == listKey.length){
                            net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(result);
                            commonResult.setResult(jsonArray);
                        }
                        //单集合输出(有key)
                        else if(1 == listKey.length){
                            resultObject = JsonUtil_Org.getValueByKey(jsonObject.getJSONObject("result"), listKey[0]);
                            commonResult.setResult(JsonUtil_Google.getGsonListByGsonString(resultObject, cls));
                        }
                        //多集合输出(多key)
                        else{
                            for(int i = 0; i < listKey.length; i++){
                                resultObject = JsonUtil_Org.getValueByKey(jsonObject.getJSONObject("result"), listKey[i]);
                                if(StringUtils.isNotEmpty(resultObject)){
                                    hashMap.put(listKey[i], JsonUtil_Google.getGsonListByGsonString(resultObject, cls));
                                }
                            }
                            commonResult.setResult(hashMap);
                        }
                    }
                } else{
                    commonResult.setResult(new JSONObject());
                }
                    return commonResult;
            }else{
                //响应失败
                commonResult.setMessage(resMsg);
                commonResult.setCode(resCode);
                commonResult.setResult(new JSONObject());
                return commonResult;
            }
        } catch (JSONException e) {
            e.printStackTrace();
            commonResult.setCode(Constants.CODE_FAIL);
            commonResult.setMessage(Constants.RETURN_SERVER_EXCEIPTION);
            commonResult.setResult(new JSONObject());
        }
        return commonResult;
    }

    /***
     * 获取响应数据
     * @param commonResult 返回结果
     * @param json 服务器数据
     * @param cls 映射对象
     * @return
     */
    public static CommonResult getCommonResult(CommonResult commonResult, String json, Class cls){
        //创建jsonObject对象
        JSONObject jsonObject;
        try {
            if(StringUtils.isEmpty(json)){
                commonResult.setMessage(Constants.RETURN_NETWORK_EXCEIPTION);
                commonResult.setCode(Constants.CODE_FAIL);
                return commonResult;
            }
            jsonObject = new JSONObject(json);
            //获取返回编码
            String resCode = JsonUtil_Org.getValueByKey(jsonObject, Constants.RESCODE);
            //获取返回消息
            String resMsg = JsonUtil_Org.getValueByKey(jsonObject, Constants.RESMSG);
            //获取返回结果
            String result = JsonUtil_Org.getValueByKey(jsonObject, Constants.RESULT);
            //响应成功
            if(Constants.CODE_SUCCESS.equalsIgnoreCase(resCode)) {
                commonResult.setMessage(resMsg);
                commonResult.setCode(resCode);
                if(cls != null){
                    commonResult.setResult(JsonUtil_Google.getGsonObjectByObject(result, cls));
                } else {
                    commonResult.setResult(new JSONObject());
                }
                return commonResult;
            }else{
                //响应失败
                commonResult.setMessage(resMsg);
                commonResult.setCode(resCode);
                commonResult.setResult(new JSONObject());
                return commonResult;
            }
        } catch (JSONException e) {
            e.printStackTrace();
            commonResult.setCode(Constants.CODE_FAIL);
            commonResult.setResult(new JSONObject());
            commonResult.setMessage(Constants.RETURN_SERVER_EXCEIPTION);
        }
            return commonResult;
    }



    /***
     * 获取响应数据
     * @param commonResult 返回结果
     * @param json 服务器数据
     * @param cls 映射对象
     * @return
     */
    public static CommonResult getOpenAPICommonResult(CommonResult commonResult, String json, Class cls){
        //创建jsonObject对象
        JSONObject jsonObject;
        try {
            if(StringUtils.isEmpty(json)){
                commonResult.setMessage(Constants.RETURN_NETWORK_EXCEIPTION);
                commonResult.setCode(Constants.CODE_FAIL);
                return commonResult;
            }
            jsonObject = new JSONObject(json);
            //获取返回编码
            String resCode = JsonUtil_Org.getValueByKey(jsonObject, Constants.ERRORCODE);
            //获取返回消息
            String resMsg = JsonUtil_Org.getValueByKey(jsonObject, Constants.ERRORMESSAGE);
            //获取返回结果
            String result = JsonUtil_Org.getValueByKey(jsonObject, Constants.DATA);

            //响应成功
            if(Const.HKWS_SUCCESS_0.equalsIgnoreCase(resCode)) {
                commonResult.setCode(Constants.CODE_SUCCESS);
                if(cls != null){
                    try{
                            //单个参数返回，转换出现异常
                            commonResult.setResult(JsonUtil_Google.getGsonObjectByObject(result, cls));
                        }catch(Exception e){
                            commonResult.setResult(result);
                        }
                } else {
                    commonResult.setResult(new JSONObject());
                }
                    return commonResult;
            }else{
                //响应失败
                commonResult.setCode(Constants.CODE_FAIL);
                commonResult.setMessage(resMsg);
                return commonResult;
            }
        } catch (JSONException e) {
            e.printStackTrace();
            commonResult.setCode(Constants.CODE_FAIL);
            commonResult.setMessage(Constants.RETURN_SERVER_EXCEIPTION);
        }
            return commonResult;
    }






}

